import type { UserModelState } from '@/models/userModel';
import { login } from '@/services/home/api';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { connect, history, useModel } from '@umijs/max';
import { Button, Form, Input, message } from 'antd';
import React, { forwardRef } from 'react';
import styles from './index.less';

interface Props {
  refInstance: any;
  usermodel: UserModelState;
  dispatch: any;
}

const Index: React.FC<Props> = (props) => {
  const { dispatch } = props;
  const { initialState, refresh, setInitialState } = useModel('@@initialState');

  const handleSubmit = async (e: HOMEAPI.LoginForm) => {
    e.grant_type = 'password';
    e.scope = 'all';
    e.client_id = 'admin';
    e.client_secret = '112233';
    // e.password = aesEncryption(e.password || '');
    const res = await login(e);
    // token过期时间
    res.tokenSurvivalTime = Date.now() + res.expires_in * 1000;
    // 缓存到本地
    localStorage.setItem(BASE_TOKEN_NAME, JSON.stringify(res));
    // 获取用户信息
    const {
      code,
      message: messageText,
      data,
    } = (await initialState?.fetchUserInfo?.(
      'login',
    )) as unknown as COMMON.BaseSuccess<HOMEAPI.CurrentUser>;
    if (code === 200) {
      message.success('登录成功!');
      await setInitialState((s: any) => ({
        ...s,
        currentUser: data,
      }));
      refresh();
      dispatch({ type: 'usermodel/changeIsShowLoginModal', payload: false });
      history.replace('/plaza');
    } else {
      message.error(messageText);
    }
    return true;
  };
  return (
    <div className={styles.loginWrapper}>
      <div className={styles.login}>
        <div className={styles.title}>博客登录</div>
        <Form
          name="登录"
          className={styles.loginForm}
          initialValues={{ remember: true }}
          onFinish={handleSubmit}
        >
          <Form.Item name="username" rules={[{ required: true, message: '请输入用户名' }]}>
            <Input
              prefix={<UserOutlined className={styles.siteFormItemCcon} />}
              placeholder="请输入用户名"
            />
          </Form.Item>
          <Form.Item name="password" rules={[{ required: true, message: '请输入密码' }]}>
            <Input
              prefix={<LockOutlined className={styles.siteFormItemCcon} />}
              type="password"
              placeholder="密码"
            />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" className={styles.loginFormButton}>
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default connect(({ usermodel }: { usermodel: UserModelState }) => ({
  usermodel,
}))(forwardRef((props: any, ref) => <Index {...props} refInstance={ref} />));
